package com.jay.media.kit

import com.google.gson.Gson
import com.google.gson.JsonObject
import com.google.gson.reflect.TypeToken

/**
 * @author xuzhou4
 * @date 2022/2/25
 */
object GsonUtils {

    var gson: Gson = Gson()

    fun toJson(data: Any): String {
        return gson.toJson(data)
    }

    fun <T> fromJson(json: String, clazz: Class<T>): T {
        return gson.fromJson(json, clazz)
    }

    fun <T> fromJsonArray(json: String, clazz: Class<T>): List<T> {
        var list: List<JsonObject> = gson.fromJson(
            json,
            object : TypeToken<List<JsonObject>>() {}.type
        ) ?: ArrayList()

        var data: MutableList<T> = ArrayList()
        for (m in list) {
            data.add(gson.fromJson(m, clazz))
        }

        return data
    }
}